package com.zhongmai.yzfgrabanorder.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zhongmai.yzfgrabanorder.Adapter.AppealRecyclerViewAdapter;
import com.zhongmai.yzfgrabanorder.R;
import com.zhongmai.yzfgrabanorder.base.BaseActivity;
import com.zhongmai.yzfgrabanorder.bean.AppealOrderItemBean;
import com.zhongmai.yzfgrabanorder.utils.Constants;
import com.zhongmai.yzfgrabanorder.utils.EncryptUtils;
import com.zhongmai.yzfgrabanorder.utils.HttpXUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.zhongmai.yzfgrabanorder.utils.Constants.user;

public class HistoricalOrdersActivity extends BaseActivity {
    @BindView(R.id.mTV_title)
    TextView mTV_title;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.mSRL)
    SmartRefreshLayout mSRL;
    @BindView(R.id.mRV_all_appeal_orders)
    RecyclerView mRV_all_appeal_orders;


    private boolean refreshType = true;
    private int page = 1;
    private int oldListSize;
    private int newListSize;
    private int addListSize;
    private AppealRecyclerViewAdapter adapter;
    private List<AppealOrderItemBean> mList = new ArrayList<>();


    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_historical_orders);
    }


    @OnClick({R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                this.finish();
                break;
        }
    }

    @Override
    protected void initView() {
        isQuit = false;
        setStatusBar();
        mTV_title.setText("历史订单");
        iv_back.setVisibility(View.VISIBLE);

    }

    @Override
    protected void initData() {
        // 开启自动加载功能（非必须）
        //        mSRL.setEnableAutoLoadMore(true);
        //        mSRL.setEnableRefresh(false);//关闭下拉刷新
        mSRL.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        logMag("加载page：" + page);
                        refreshType = true;
                        page = 1;
                        parsingMovieListJson();
                        refreshLayout.finishRefresh();
                        refreshLayout.resetNoMoreData();//setNoMoreData(false);
                        mSRL.setEnableRefresh(false);
                    }
                }, 1000);
            }
        });
        mSRL.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshType = false;
                        //                        if (page > 2) {
                        //                            showToast("暂无更多的数据啦");
                        //                            // 将不会再次触发加载更多事件
                        //                            refreshLayout.finishLoadMoreWithNoMoreData();
                        //                            return;
                        //                        }
                        parsingMovieListJson();
                        refreshLayout.setEnableLoadMore(true);
                        refreshLayout.finishLoadMore();
                    }
                }, 1000);
            }
        });
        //触发自动刷新
        mSRL.autoRefresh();
    }

    private void parsingMovieListJson() {
        // 从assets目录中获取json数据，在真实的项目开发中需要通过网络请求从服务器json数据
        //        String jsonData = BaseTools.getAssetsJson(this, "movie" + page + ".json");
        if (refreshType && mList != null) {
            mList.clear();
            oldListSize = 0;
        } else {
            oldListSize = mList.size();
        }
        RequestParams params = new RequestParams(Constants.Url + Constants.successTradeList);
        try {
            params.addHeader("Authorization", user);
            JSONObject json = new JSONObject();

            json.put("pageSize", Constants.page_size);
            json.put("page", page);
            logMag("请求page：" + page);
            String def = EncryptUtils.encrypt(json.toString(), Constants.encrypt_key, Constants.encrypt_iv);
            String mdf = EncryptUtils.md5(def + Constants.encrypt_key).toUpperCase();
            params.addBodyParameter("def", def);
            params.addParameter("mdf", mdf);
        } catch (JSONException e1) {
            e1.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        HttpXUtils.xUtilsPostRequest(this, params, new HttpXUtils.MyCallback() {
            @Override
            public void myResult(String result) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String code = jsonObject.getString("code");
                    if (code.equals("100000")) {
                        String jsonData = jsonObject.getString("data");
                        if (!"[]".equals(jsonData)&&!"{}".equals(jsonData)){
                            Gson gson = new Gson();
                            List<AppealOrderItemBean> movieDataModelList = gson.fromJson(jsonData,
                                    new TypeToken<ArrayList<AppealOrderItemBean>>() {
                                    }.getType());
                            for (AppealOrderItemBean itemBean : movieDataModelList) {
                                mList.add(itemBean);
                                logMag("条目数：" + mList.size());
                            }
                            updateLayout();
                        } else {
                            if(mList.size()<=0) {
                                mSRL.setBackground(getResources().getDrawable(R.mipmap.png_no_order));
                                showToast("无订单信息...");
                            }else {
                                showToast("无新增订单信息...");
                            }
                        }
                    } else {
                        String message = jsonObject.getString("message");
                        showToast(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String err) {

            }
        }, true);


    }

    private void updateLayout() {
        mSRL.setBackground(getResources().getDrawable(R.color.CS_black_2_percent));
        newListSize = mList.size();
        addListSize = newListSize - oldListSize;
        if (refreshType) {
            // 设置RecyclerView样式为竖直线性布局
            mRV_all_appeal_orders.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            adapter = new AppealRecyclerViewAdapter(this, mList);
            // 设置分割线
            //            mRV_all_appeal_orders.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager
            //            .VERTICAL));
            mRV_all_appeal_orders.setAdapter(adapter);
        } else {
            adapter.notifyItemRangeInserted(mList.size() - addListSize, mList.size());
            adapter.notifyItemRangeChanged(mList.size() - addListSize, mList.size());
        }

        page++;

        mRV_all_appeal_orders.setVisibility(View.VISIBLE);
        // dialog.dismiss();
        // item条目的点击事件回调
        adapter.setItemClikListener(new AppealRecyclerViewAdapter.OnItemClikListener() {
            // 短按点击事件回调
            @Override
            public void onItemClik(View view, int position) {
                getOrderInfo(mList.get(position).getOrderId());
            }

            // 长按点击事件回调
            @Override
            public void onItemLongClik(View view, int position) {

            }
        });
    }


    private void getOrderInfo(String orderId) {
        RequestParams params = new RequestParams(Constants.Url + Constants.orderInfo);
        try {
            params.addHeader("Authorization", user);
            JSONObject json = new JSONObject();

            json.put("orderId", orderId);
            String def = EncryptUtils.encrypt(json.toString(), Constants.encrypt_key, Constants.encrypt_iv);
            String mdf = EncryptUtils.md5(def + Constants.encrypt_key).toUpperCase();
            params.addBodyParameter("def", def);
            params.addParameter("mdf", mdf);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpXUtils.xUtilsPostRequest(this, params, new HttpXUtils.MyCallback() {
            @Override
            public void myResult(String result) {
                logMag("------------" + result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String code = jsonObject.getString("code");
                    if (code.equals("100000")) {
                        String data = jsonObject.getString("data");
                        if (!data.equals("{}")){
                            Intent intent = new Intent(HistoricalOrdersActivity.this, OrderInfoActivity.class);
                            Bundle bundle = new Bundle();
                            //传输的内容仍然是键值对的形式
                            bundle.putString("order", data);//回发的消息,hello world from
                            // secondActivity!
                            intent.putExtras(bundle);
                            startActivityForResult(intent, 2);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String err) {

            }
        }, true);

    }
}
